import { errorRes } from '@/utils/responseModel'
import { getType } from '@/utils/utils'
import Koa from 'koa'

const customError = () => {
    return async (ctx: Koa.ParameterizedContext<Koa.DefaultState, Koa.DefaultContext, any>, next: Koa.Next) => {
        try {
            await next() // 处理请求
        } catch (e: any) {
            if (e instanceof errorRes) {
                ctx.body = e
                console.warn(e)
            } else if (getType(e) === 'string') {
                ctx.body = new errorRes(e.message ?? e)
                console.warn(e)
            } else {
                throw e
            }
        }
    }
}

export {
    customError
}